package com.jiuye.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuye.common.BaseContext;
import com.jiuye.common.CustomException;
import com.jiuye.common.GlobalConstant;
import com.jiuye.entity.ShoppingCart;
import com.jiuye.mapper.IShoppingCartMapper;
import com.jiuye.service.IShoppingCartService;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 购物车显示接口业务层实现类
 *
 * @author likeWen
 * @since 2022/11/7 11:49
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<IShoppingCartMapper, ShoppingCart> implements IShoppingCartService {
    /**
     * 购物车减号按钮
     */
    @Override
    public ShoppingCart subShoppingCart(ShoppingCart shoppingCartParam) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentUserId());
        if (shoppingCartParam.getDishId() != null) {
            queryWrapper.eq(ShoppingCart::getDishId, shoppingCartParam.getDishId());
        } else if (shoppingCartParam.getSetmealId() != null) {
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCartParam.getSetmealId());
        } else {
            throw new CustomException(GlobalConstant.FAILED);
        }
        ShoppingCart shoppingCart = this.getOne(queryWrapper);
        Optional.ofNullable(shoppingCart).orElseThrow(() -> new CustomException(GlobalConstant.SUCCESS));
        if (shoppingCart.getNumber() == 1) {
            this.removeById(shoppingCart);
            shoppingCart.setNumber(0);
        } else {
            shoppingCart.setNumber(shoppingCart.getNumber() - 1);
            this.updateById(shoppingCart);
        }
        return shoppingCart;
    }
}
